'use strict';

/**
 * 测试 OpenID 查询功能
 * 用于诊断登录问题
 */

exports.main = async (event, context) => {
  const db = uniCloud.database();
  const dbCmd = db.command;
  
  const { action, testOpenid } = event;
  
  switch (action) {
    case 'testQuery': {
      // 测试查询语法
      try {
        console.log('[测试] 开始测试查询，testOpenid:', testOpenid);
        
        const result = await db.collection('users').where(dbCmd.or([
          { wx_openid: testOpenid },
          { 'wx_openid.mp': testOpenid }
        ])).get();
        
        console.log('[测试] 查询成功，找到', result.data.length, '个用户');
        
        return {
          code: 0,
          message: '查询成功',
          data: {
            count: result.data.length,
            users: result.data.map(u => ({
              _id: u._id,
              nickname: u.nickname,
              wx_openid: u.wx_openid,
              wx_openid_type: typeof u.wx_openid
            }))
          }
        };
      } catch (e) {
        console.error('[测试] 查询失败:', e);
        return {
          code: 500,
          message: '查询失败',
          error: e.message,
          stack: e.stack
        };
      }
    }
    
    case 'listAllUsers': {
      // 列出所有用户的 wx_openid 格式
      try {
        const result = await db.collection('users').limit(10).get();
        
        return {
          code: 0,
          message: '查询成功',
          data: {
            count: result.data.length,
            users: result.data.map(u => ({
              _id: u._id,
              nickname: u.nickname,
              wx_openid: u.wx_openid,
              wx_openid_type: typeof u.wx_openid,
              wx_openid_has_mp: u.wx_openid && typeof u.wx_openid === 'object' ? !!u.wx_openid.mp : false
            }))
          }
        };
      } catch (e) {
        return {
          code: 500,
          message: '查询失败',
          error: e.message
        };
      }
    }
    
    case 'fixUserOpenid': {
      // 修复指定用户的 wx_openid 格式
      const { userId, openid } = event;
      
      if (!userId || !openid) {
        return {
          code: 400,
          message: '缺少参数: userId 或 openid'
        };
      }
      
      try {
        // 获取用户当前信息
        const userRes = await db.collection('users').doc(userId).get();
        if (userRes.data.length === 0) {
          return {
            code: 404,
            message: '用户不存在'
          };
        }
        
        const user = userRes.data[0];
        console.log('[修复] 用户当前 wx_openid:', user.wx_openid);
        
        // 构建新的 wx_openid
        let newWxOpenid;
        if (typeof user.wx_openid === 'object' && user.wx_openid !== null) {
          // 已经是对象，保留现有字段并更新 mp
          newWxOpenid = { ...user.wx_openid, mp: openid };
        } else {
          // 字符串或不存在，创建新对象
          newWxOpenid = { mp: openid };
        }
        
        console.log('[修复] 新的 wx_openid:', newWxOpenid);
        
        // 更新数据库
        await db.collection('users').doc(userId).update({
          wx_openid: newWxOpenid
        });
        
        return {
          code: 0,
          message: '修复成功',
          data: {
            userId,
            oldWxOpenid: user.wx_openid,
            newWxOpenid: newWxOpenid
          }
        };
      } catch (e) {
        console.error('[修复] 失败:', e);
        return {
          code: 500,
          message: '修复失败',
          error: e.message
        };
      }
    }
    
    default:
      return {
        code: 400,
        message: '未知操作',
        usage: {
          testQuery: '测试查询: { action: "testQuery", testOpenid: "oABC123" }',
          listAllUsers: '列出所有用户: { action: "listAllUsers" }',
          fixUserOpenid: '修复用户OpenID: { action: "fixUserOpenid", userId: "xxx", openid: "oABC123" }'
        }
      };
  }
};

